package com.fzu.mmdbproxyframework.dispatcher;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WeightedRoundRobinScheduling {
	/**
	 * 
	 */
	public WeightedRoundRobinScheduling() {
		super();
	}

	static WeightedRoundRobinScheduling obj;
	private List<Server> serverList; // 服务器集合
	Boolean flag = true;
	public WeightedRoundRobinScheduling(List<Server> serverList) {
		this.serverList = serverList;
	}
	public Server GetBestServer() {
		Server server = null;
		Server best = null;
		int total = 0;
		for (int i = 0, len = serverList.size(); i < len; i++) {
			// 当前服务器对象
			server = serverList.get(i);
			// 当前服务器已宕机，排除
			if (server.down) {
				continue;
			}
			server.currentWeight += server.effectiveWeight;
			total += server.effectiveWeight;
			if (server.effectiveWeight < server.weight) {
				server.effectiveWeight++;
			}
			if (best == null || server.currentWeight > best.currentWeight) {
				best = server;
			}
		}
		if (best == null) {
			return null;
		}
		best.currentWeight -= total;
		best.checkedDate = new Date();
		return best;
	}

	public void add(String ip) {
		Server s = new Server(ip);
		serverList.add(s);
	}

	public Server getServer(int i) {
		if (i < serverList.size()) {
			return serverList.get(i);
		}
		return null;
	}

	public static void main(String[] args) {
		ArrayList<Server> serverList = new ArrayList<Server>();
		serverList.add(new Server("192.168.2.100"));
		serverList.add(new Server("192.168.2.101"));
		obj=new WeightedRoundRobinScheduling(serverList);
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
		System.out.println(obj.GetBestServer().getIp());
//		obj.start();
		// new WeightedRoundRobinScheduling().run();
		// Map<String,Integer> countResult = new HashMap<String,Integer>();
		// for (int i = 0; i < 30000; i++) {
		// Server s = obj.GetBestServer();
		// String log = "ip:"+s.ip;
		// if(countResult.containsKey(log)){
		// countResult.put(log,countResult.get(log)+1);
		// }else{
		// countResult.put(log,1);
		// }
		// System.out.println(log);
		// if(i==4)
		// obj.add(2);
		// 动态停止服务器
		// if(i==8){
		// obj.getServer(2).setDown(true);
		// obj.getServer(3).setDown(true);
		// }
		// }

		// for(Entry<String, Integer> map : countResult.entrySet()){
		// System.out.println("服务器 "+map.getKey()+" 请求次数： "+map.getValue());
		// }
	}
	public List<Server> getServerList() {
		return serverList;
	}
	public void setServerList(List<Server> serverList) {
		this.serverList = serverList;
	}
}